package reading.web.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import reading.common.enums.ErrorEnum;
import reading.common.exception.*;
import reading.common.pojos.Success;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Project: message-management
 * Package: com.mm.web.advice
 *
 * @author : txw
 * @date : 2018/4/19 17:29
 */
@ControllerAdvice
@ResponseBody
public class ExceptionHandlerAdvice {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);

    @ExceptionHandler(AbstractHlBaseException.class)
    public ResponseEntity<?> handleException(AbstractHlBaseException e) {
        logger.error("异常", e);
        HttpStatus status = HttpStatus.OK;
        if (e instanceof HlUnauthorizedException) {
            status = HttpStatus.UNAUTHORIZED;
        }
        boolean notFind = e.getErrCode() == ErrorEnum.NOT_FIND_DATA.getValue() || e.getErrCode() == ErrorEnum.FILE_NOT_FIND.getValue() || e instanceof HlNotFoundException || e instanceof HlNotImplementException;
        if (notFind) {
            status = HttpStatus.NOT_FOUND;
        }
        if (e instanceof HlPrivilegeAuthException) {
            status = HttpStatus.FORBIDDEN;
        }
        if (e instanceof HlValidateException) {
            status = HttpStatus.NOT_ACCEPTABLE;
        }
        if (e instanceof HlDbOptException || e instanceof HlIoException) {
            status = HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return new ResponseEntity<>(Success.success(e.getErrCode(), e.getErrMsg(), e.getData(), null), status);
    }

    @ExceptionHandler(value=TypeMismatchException.class)
    public ModelAndView exceptionResolver(Exception ex, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        mav.addObject("ex", ex);
        //发生异常的路径
        mav.addObject("url",request.getRequestURL());
        mav.setViewName("error");
        return mav;
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> handle(MethodArgumentNotValidException ex) {
        List<FieldError> errors = ex.getBindingResult().getFieldErrors();
        String es = errors.get(errors.size() - 1).getDefaultMessage();
        return new ResponseEntity<>(Success.success(ErrorEnum.PARAMS_FORMAT_ERROR.getValue(), es, es, null), HttpStatus.OK);
    }
}
